﻿using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using Microsoft.Web.Preview.Services;
using Lx.Web.Common.UI;
using Lx.Web.Common.ControlsUI;
using Model;
using BLF.WWW_WWW.Learn;

namespace WebServices.User
{
    /// <summary>
    /// Learn 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.italki.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    public class Public : System.Web.Services.WebService
    {
        /// <summary>
        /// outList[0]:NL没有登录，F：数据操作失败outList[1]是否朋友outList[2]是否已经发出联系信息outList[3]对方是否允许联系
        /// outList[4]：对方是否允许Email通知outList[5]朋友昵称outList[6]我的昵称outList[7]朋友Email,outList[8]string[]
        /// {CT047,CT048,C0047,C0056,CT051,C0069,CT041,C0064,CT049,CT050,C1002,C1006,C0022}
        /// </summary>
        /// <param name="sFriendMemberNo">朋友会员号</param>
        /// <returns></returns>
        [WebMethod]
        public ArrayList MemberRelation(string sFriendMemberNo)
        {
            ArrayList outList;
            if (HttpContext.Current.User.Identity.Name == "")
            {
                outList = new ArrayList();
                outList.Add("NL");
                return outList;
            }

            CommonMessage comMes = BLF.WWW_WWW.Contact.Contacts.MemberRelation(HttpContext.Current.User.Identity.Name, sFriendMemberNo, out outList);
            if (!comMes.State)
            {
                outList = new ArrayList();
                outList.Add("F");
                return outList;
            }
            if (comMes.Effect == 1)
            {
                bool EmailOption = ((1 & ((int)outList[3])) == 1);
                outList.RemoveAt(3);
                outList.Insert(3, EmailOption);
                outList.Insert(0, "S");
                string sFN = (string)outList[5];
                string[] sText = new string[] { Lx.Web.Common.Resource.GetText(Globals.Language, "CT047", new string[] {sFN}),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "CT048"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C0047"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C0056"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "CT051", new string[] {sFN}),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C0069"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "CT041", new string[] {sFN}),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C0064"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "CT049", new string[] {sFN}),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "CT050", new string[] {sFN}),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C1002"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C1006"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C0078")
                };
                outList.Add(sText);
            }
            else if(comMes.Effect==2){
                outList.Add("myFull");
                string[] sText = new string[] {
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C0064"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C0078"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "CT067")
                };
                outList.Add(sText);
            }
            else
            {
                outList.Add("fFull");
                string[] sText = new string[] {
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C0064"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "C0078"),
                    Lx.Web.Common.Resource.GetText(Globals.Language, "CT068")
                };
                outList.Add(sText);
            }
            return outList;
        }

        /// <summary>
        /// 邀请新朋友
        /// </summary>
        /// <param name="fMemberno">朋友编号</param>
        /// <param name="isEmail">是否email通知</param>
        /// <param name="fNickName">朋友昵称</param>
        /// <param name="myNickName">我的昵称</param>
        /// <param name="eMail">mail地址</param>
        /// <param name="msg">消息</param>
        /// <returns></returns>
        [WebMethod]
        public CommonMessage AddNewFriend(string fMemberno, bool isEmail,string fNickName, string myNickName, string eMail, string msg)
        {
            string myMemberno = HttpContext.Current.User.Identity.Name;
            if (myMemberno == "")
            {
                return new CommonMessage();
            }
            CommonMessage comMes = BLF.WWW_WWW.Contact.Contacts.AddNewFriend(myMemberno, fMemberno);//1:添加成功, 0:好友数量超限, 2:已经是联系人
            if (isEmail)
            {
                if (myMemberno == "" || fMemberno == "")
                {
                    comMes.Msg = "1";
                    return comMes;
                }
                if (!System.Text.RegularExpressions.Regex.IsMatch(eMail, "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"))
                {
                    comMes.Msg = "2";
                    return comMes;
                }
                else
                {
                    BaseControl baseControl = new BaseControl();
                    string eSubject = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/InvitationSend.xml", Globals.Language)), Globals.Language), "email", "subject", "");
                    string eBody = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/InvitationSend.xml", Globals.Language)), Globals.Language), "email", "body", "");
                    new System.Threading.Thread(new System.Threading.ThreadStart(delegate
                    {
                        eSubject = eSubject.Replace("{0}", myNickName);
                        eBody = eBody.Replace("{0}", myNickName).Replace("{1}", fNickName).Replace("{2}", myMemberno).Replace("{3}", fMemberno).Replace("{4}", msg);
                        MsMailSend.SendMail(eSubject, eBody, eMail, null, true);
                    })).Start();
                    comMes.Msg = "0";
                }
            }
            return comMes;
        }

        
        /// <summary>
        /// 获取ShareRes相关信息（0：当前会员好友数量、1：朋友信息（号、昵称）、2：当前会员昵称名、3:文字相关、4：分页、5：我的编号）
        /// </summary>
        /// <param name="memberno">当前会员号</param>
        /// <param name="pageIndex">pageIndex</param>
        /// <param name="pageSize">pageSize</param>
        /// <returns>ArrayList（0：所有朋友（号、昵称）、1：当前会员昵称名）</returns>
        [WebMethod]
        public ArrayList GetShareResInfo(int pageIndex, int pageSize)
        {
            ArrayList outList;
            string memberno = HttpContext.Current.User.Identity.Name;
            if (memberno == "")
            {
                outList = new ArrayList();
                outList.Add("NL");
                return outList;
            }

            outList = BLF.WWW_WWW.Contact.Contacts.GetShareResInfo(memberno, pageIndex, pageSize);
            if (outList == null)
            {
                outList = new ArrayList();
                outList.Add("F");
                return outList;
            }            
            string[] sText = new string[] { 
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0047"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0056"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0064"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR000"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR001"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR002"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR003"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR005"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR006"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR009"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR010"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR011"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR012"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR014"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR017"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR018"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "SR016")
            };
            outList.Add(sText);
            outList.Add(new BLF.PageableObject((int)outList[0], pageIndex, pageSize));
            outList.Add(memberno);
            return outList;
        }

        /// <summary>
        /// 获取会员好友列表(Nickname,MemberNo,Avatar)(Share)
        /// </summary>
        /// <param name="memberno">当前会员号</param>
        /// <param name="pageIndex">pageIndex</param>
        /// <param name="pageSize">pageSize</param>        
        /// <returns>ArrayList（0好友列表 1PageableObject）</returns>
        [WebMethod]
        public ArrayList GetMemberFriends(string memberno, int pageIndex, int pageSize)
        {
            return BLF.WWW_WWW.Contact.Contacts.GetMemberFriends(memberno, pageIndex, pageSize);
        }
        /// <summary>
        /// 发送邮件(Shareo.xml)
        /// </summary>
        /// <param name="fromName">发送者昵称名</param>
        /// <param name="fEmails">被发送者email</param>
        /// <param name="shareContent">共享内容</param>
        /// <param name="SharedURL">共享url</param>
        /// <returns>CommonMessage</returns>
        [WebMethod]
        public CommonMessage SendMail(string fromName, string fEmails, string SharedURL)
        {
            CommonMessage comMes = new CommonMessage();
            string myMemberno = HttpContext.Current.User.Identity.Name;
            if (myMemberno == "" || SharedURL == "")
            {
                return comMes;
            }
            string shareContent;
            string subLink;
            SharedURL = ShareUrl(SharedURL, out shareContent, out subLink);
            BaseControl baseControl = new BaseControl();
            string eSubject = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/Shareo.xml", Globals.Language))), "email", "subject", "");
            string eBody = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/Shareo.xml", Globals.Language))), "email", "body", "");
            string[] emails = fEmails.Split(',');
            new System.Threading.Thread(new System.Threading.ThreadStart(delegate
            {
                for (int i = 0; i < emails.Length; i++)
                {
                    if (System.Text.RegularExpressions.Regex.IsMatch(emails[i], "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"))
                    {
                        eSubject = eSubject.Replace("{0}", fromName).Replace("{2}", subLink);
                        eBody = eBody.Replace("{0}", fromName).Replace("{1}", SharedURL).Replace("{2}", shareContent == "" ? SharedURL : shareContent).Replace("{3}", subLink);
                        MsMailSend.SendMail(eSubject, eBody, emails[i], null, true);
                    }
                }
            })).Start();
            return comMes;
        }
        /// <summary>
        /// 发送邮件(Sharei.xml)
        /// </summary>
        /// <param name="fromName">发送者昵称名</param>
        /// <param name="friendsMn">被发送者email列表</param>
        /// <param name="msg">信息</param>
        /// <param name="SharedURL">共享url</param>
        /// <param name="CheckAOrF">是否全选标记（true表示全选、如果friendsMn不为空表示不选择这些人）</param>
        /// <returns>CommonMessage</returns>
        [WebMethod]
        public CommonMessage SendItalkiMail(string fromName, string friendsMns, string SharedURL, bool checkAOrF)
        {
            CommonMessage comMes = new CommonMessage();
            string myMemberno = HttpContext.Current.User.Identity.Name;
            if (myMemberno == "" || SharedURL == "" || (friendsMns == ""&&!checkAOrF))
            {
                return comMes;
            }
            string shareContent;
            string subLink;
            SharedURL = ShareUrl(SharedURL, out shareContent, out subLink);
            BaseControl baseControl = new BaseControl();
            string eSubject = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/Sharei.xml", Globals.Language))), "email", "subject", "");
            string eBody = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/Sharei.xml", Globals.Language))), "email", "body", "");
            eSubject = eSubject.Replace("{0}", fromName).Replace("{2}", subLink);
            eBody = eBody.Replace("{0}", fromName).Replace("{1}", SharedURL).Replace("{2}", shareContent == "" ? SharedURL : shareContent).Replace("{3}", subLink).Replace("{4}", myMemberno);

            BLF.WWW_WWW.Contact.Contacts.ShareResSendMail(myMemberno, friendsMns, eSubject, eBody, checkAOrF);            
            return comMes;
        }
        /// <summary>
        /// 获取共享标题
        /// </summary>
        /// <param name="url">url地址</param>
        /// <param name="shareContent">输出共享内容(标题)</param>
        /// <param name="subLink">输出共享连接内容</param>
        /// <returns>共享地址</returns>
        private string ShareUrl(string url,out string shareContent,out string subLink)
        {
            shareContent = "";
            int type = 0;
            string numberno = "";
            url = url.ToLower();
            subLink = "link";
            if (url.StartsWith(System.Configuration.ConfigurationManager.AppSettings["WWWHost"].TrimEnd('/').ToLower() + "/answers/question/"))
            {//取出问题ID
                string[] quesArr = url.Split('/');
                string question = quesArr[quesArr.Length - 1];
                string[] strArr = question.Split('-');
                if (strArr.Length == 1)
                {
                    numberno = strArr[0].Split('.')[0];
                }
                else
                {
                    numberno = strArr[0];
                }
                url = System.Configuration.ConfigurationManager.AppSettings["WWWHost"].TrimEnd('/').ToLower() + "/answers/question/" + numberno + ".htm";//移除ID后参数
                //int index = url.IndexOf("QuesID=");
                //numberno = url.Substring(index + "QuesID=".Length);
                type = 1;
                subLink = "question";

            }
            else if (url.StartsWith(System.Configuration.ConfigurationManager.AppSettings["WWWHost"].TrimEnd('/').ToLower() + "/files/doc/"))
            {//取出文件ID
                string[] fileArr = url.Split('/');
                string file = fileArr[fileArr.Length - 1];
                numberno = file.Split('.')[0];
                url = System.Configuration.ConfigurationManager.AppSettings["WWWHost"].TrimEnd('/').ToLower() + "/files/doc/" + numberno + ".htm";//移除ID后参数
                type = 2;
                subLink = "file";
            }
            else if (url.StartsWith(System.Configuration.ConfigurationManager.AppSettings["WWWHost"].TrimEnd('/').ToLower() + "/files/comment-"))
            {//http://local.italki.com/files/comment-1-7c61f813-b2e1-4c96-b123-981cb042ad23.htm#
                string[] fileArr = url.Split('-');
                string file = fileArr[2] + "-" + fileArr[3] + "-" + fileArr[4] + "-" + fileArr[5] + "-" + fileArr[6];
                numberno = file.Split('.')[0];
                url = System.Configuration.ConfigurationManager.AppSettings["WWWHost"].TrimEnd('/').ToLower() + "/files/comment-1-" + numberno + ".htm";//移除ID后参数
                type = 2;
                subLink = "file";
            }
            if (type != 0)
            {
                shareContent = BLF.WWW_WWW.Contact.Contacts.Title(type, numberno);
            }
            return url;
        }
        [WebMethod]
        public ArrayList GetFeedEmail()
        {
            ArrayList outList=new ArrayList();
            string femail ="";
            string memberno = HttpContext.Current.User.Identity.Name;
            if (HttpContext.Current.User.Identity.Name !="")
            {
                femail =BLF.WWW_User.Users.User.GetUserEmail(HttpContext.Current.User.Identity.Name);
            }
            outList.Add(femail);
            string[] sText = new string[] { Lx.Web.Common.Resource.GetText(Globals.Language, "FK029"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "FK030"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "FK031"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "FK032"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "FK033"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0043"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0110"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0056"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C1007"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "PB010"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0064"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C1006")                
            };
            outList.Add(sText);
            return outList;
        }
        [WebMethod]
        public CommonMessage AddjsFeedBackCat( string Email,  string CateID, string Content, string PageUrl)
        {
            CommonMessage cm = BLF.WWW_WWW.Feedback.Feedback.AddFeedback(HttpContext.Current.User.Identity.Name, Email, "", CateID, Content, PageUrl);
            return cm;
        }
        /// <summary>
        /// 登录文字
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public string[] GetLoginRes()
        {
            string lan = Globals.Language;
            return new string[]{
           Lx.Web.Common.Resource.GetText(lan, "C0071"),
           Lx.Web.Common.Resource.GetText(lan, "C1013"),
           Lx.Web.Common.Resource.GetText(lan, "UR004"),
            Lx.Web.Common.Resource.GetText(lan, "UR009"),
            Lx.Web.Common.Resource.GetText(lan, "UR013"),
            Lx.Web.Common.Resource.GetText(lan, "UR014"),
            Lx.Web.Common.Resource.GetText(lan, "UR015"),
            Lx.Web.Common.Resource.GetText(lan, "UR016"),
            Lx.Web.Common.Resource.GetText(lan, "UR073")};
        }
        [WebMethod]
        public ArrayList GetMail(string memberno)
        {
            ArrayList outList = new ArrayList();
            string lan = "";
            string name = "";
            name = BLF.WWW_User.Users.User.GetUserName(memberno, out lan);
            lan = memberno + "(" + name + ")";
            outList.Add(lan);
            string[] sText = new string[] { Lx.Web.Common.Resource.GetText(Globals.Language, "PB113"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0108"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0047"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0079"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0064"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C1006"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "PB114")
            };
            outList.Add(sText);
            return outList;
        }
        [WebMethod]
        public bool WriteLetter(string opmemberno, string subject, string content)
        {
            if (HttpContext.Current.User.Identity.Name != "")
            {
                if (BLF.WWW_User.UserMail.Mail.WriteInform(opmemberno, HttpContext.Current.User.Identity.Name, subject, content))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }
        [WebMethod]
        public void MaSendmail(string memberno)
        {
            Model.WWW_User.User.UserNotifiModel unm = BLF.WWW_User.Users.User.GetUserNotifiInfo(memberno);
            if (unm != null)
            {
                Int32 emailVal = unm.EmailOption;
                if ((2 & emailVal) == 2 && HttpContext.Current.User.Identity.Name!="")
                {
                    Model.WWW_User.User.UserModel bumUserTo = BLF.WWW_User.Users.User.GetDetailUserInfo(memberno);
                    string ToLng = "";
                    string FromName = BLF.WWW_User.Users.User.GetUserName(HttpContext.Current.User.Identity.Name, out ToLng);
                    string FromID = HttpContext.Current.User.Identity.Name;
                    string ToName = bumUserTo.Nickname;
                    string ToID = bumUserTo.MemberNo;
                    string ToEmail = bumUserTo.MemberEmail;
                    BaseControl baseControl = new BaseControl();
                    string eSubject = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/MailNotify.xml", Globals.Language))), "email", "subject", "");
                    string eBody = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/MailNotify.xml", Globals.Language))), "email", "body", "");
                    eSubject = eSubject.Replace("{0}", FromName);
                    eBody = eBody.Replace("{0}", FromName).Replace("{1}", ToName).Replace("{2}", FromID);
                    if (System.Text.RegularExpressions.Regex.IsMatch(ToEmail, "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"))
                    {
                        MsMailSend.SendMail(eSubject, eBody, ToEmail, null, true);
                    }
                }
            }
        }
        [WebMethod]
        public ArrayList GetTeTime()
        {
            ArrayList outList = new ArrayList();
            string[] sText = new string[] { Lx.Web.Common.Resource.GetText(Globals.Language, "TP015"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "TP017"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "TP018"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "TP019"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "TP020"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "TP021"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "TP022"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "TP023"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "TP024"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0045"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0044"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0053"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "TP315"),
                Lx.Web.Common.Resource.GetText(Globals.Language, "C0050")
                
            };
            outList.Add(sText);
            return outList;
        }
    }
}
